import { all,takeEvery,call,fork,put} from "redux-saga/effects";
import * as CONSTANT from '../constant'
import axios from "axios";
import {actionUser, actionUserError} from '../action/actionUser';

//worker
function* getUserAsync(){
    console.log('getUserAsync');
    //同步执行：阻塞式
    // let user = yield axios.get('https://jsonplaceholder.typicode.com/users/1')
    
    //call(fn,args) : 注意写法
    // let user = yield call(axios.get,'https://jsonplaceholder.typicode.com/users/1')
    // console.log(user.data);

    //fork(fn,args) : 注意写法 ,非阻塞 不会等待axios.get，直接执行后面代码
    // let user = yield fork(axios.get,'https://jsonplaceholder.typicode.com/users/1')
    // console.log(user.data); //undefined

    // 同步阻塞请求 ： 网络请求时间是三个请求接口时间之和  浪费时间
    // let user = yield axios.get('https://jsonplaceholder.typicode.com/users/1')
    // console.log(user);
    // let post = yield axios.get('https://jsonplaceholder.typicode.com/posts/1')
    // console.log(post);
    // let todo = yield axios.get('https://jsonplaceholder.typicode.com/todos/1')
    // console.log(todo);

    
    //并发请求 ： 网络请求时间是 三个请求接口其中一个最长时间
    // const [user,post,todo] = yield all([
    //     axios.get('https://jsonplaceholder.typicode.com/users/1'),
    //     axios.get('https://jsonplaceholder.typicode.com/posts/1'),
    //     axios.get('https://jsonplaceholder.typicode.com/todos/1')
    // ])

    // console.log('user',user.data,'post',post.data,'todo',todo.data);

    // const [user,post,todo] = yield all([
    //     call(axios.get,'https://jsonplaceholder.typicode.com/users/1'),
    //     call(axios.get,'https://jsonplaceholder.typicode.com/posts/1'),
    //     call(axios.get,'https://jsonplaceholder.typicode.com/todos/1'),
    // ])
    // console.log('user',user.data,'post',post.data,'todo',todo.data);

    try {
        let {data} =  yield call(axios.get,'https://jsonplaceholder.typicode.com/users/1')
        // console.log(result.data);
        // let user  = result.data
        console.log(data);
         let user  = data
        yield put(actionUser(user))
    } catch (error) {
        console.log(error);
        yield put(actionUserError(error.message))
    }
}




//watcher
export function* watchUserSaga(){
    console.log('watchUserSaga');
    yield takeEvery(CONSTANT.USER_ASYNC,getUserAsync)
}